package com.fjec.market.schedule.handler;

import com.aliyuncs.utils.StringUtils;
import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.common.ys.PaidHelper;
import com.fjec.common.ys.protocol.ResRegister;
import com.fjec.common.ys.protocol.ResSearchReg;
import com.fjec.market.entity.BizYespayRegLog;
import com.fjec.market.entity.InfoYsepayRegister;
import com.fjec.market.service.IBizYespayRegLogService;
import com.fjec.market.service.IInfoYsepayRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class YsRegisterHandler extends BaseScheduleHandler {

    @Resource
    private IInfoYsepayRegisterService ysepayRegisterService;

    @Resource
    private PaidHelper paidHelper;

    @Resource
    private IBizYespayRegLogService bizYespayRegLogService;

    public String handle(int limit, int minutes) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        // 查询超过时间未处理的进件 状态为1
        List<Long> entityIdList = ysepayRegisterService.getEntityForReg(limit, minutes);
        // 处理
        int success = 0;
        for (Long entityId : entityIdList) {
            InfoYsepayRegister entity = ysepayRegisterService.getById(entityId);
//            Long merchantNo = idGenerator.nextId();
            ResRegister resRegister = null;
            try {
                boolean register = false;
                // 进件状态查询
                if (!StringUtils.isEmpty(entity.getMerchantNo1())) {
                    String result = paidHelper.searchRegister(entity.getMerchantNo1());
                    ResSearchReg searchReg = JsonUtil.jsonToObject(result, ResSearchReg.class);
                    if (searchReg.getCode() == 10000) {
                        entity.setRegStatus(2);
                        entity.setUpdateTime(DateUtil.nowLdt());
                        ysepayRegisterService.updateById(entity);
                    } else {
                        // 进件
                        register = true;
                    }
                } else {
                    // 进件
                    register = true;
                }
                if (register) {
                    // 修改进件唯一标识
                    // 创建merchantNo = busiType-busiId-updateVer
                    StringBuilder sb = new StringBuilder();
                    sb.append(entity.getBusiType())
                            .append("-")
                            .append(entity.getBusiId().toString())
                            .append("-")
                            .append(entity.getUpdateVer());
                    entity.setMerchantNo1(sb.toString());
                    ysepayRegisterService.updateById(entity);
                    // 进件
                    resRegister = ysepayRegisterService.ysReg(entityId);
                }
                success++;
            } catch (Exception ex) {
                String guid = this.error(ex);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("guid", guid);
                errorMap.put("id", entityId);
                errorList.add(errorMap);
            }
            // 记录进件访问log
            recordLog(entity, resRegister);
        }
        String result;
        if (errorList.isEmpty()) {
            // 全部处理，无异常
            result = String.format("Handle timeout order num:[%d]", success);
        } else {
            result = String.format("Handle timeout order success num:[%d], fail:[%d], Ids:[%s]",
                    success, errorList.size(), JsonUtil.toJson(errorList));
        }
        return result;
    }


    private void recordLog(InfoYsepayRegister entity, ResRegister resRegister) {
        // 银盛进件log表
        BizYespayRegLog logEntity = new BizYespayRegLog();
        logEntity.setRegId(entity.getId());
        logEntity.setCustName(entity.getCustName());
        logEntity.setMerchantNo(entity.getMerchantNo1());
        logEntity.setCreateTime(DateUtil.nowLdt());
        logEntity.setOptType(1);
        if (resRegister != null) {
            logEntity.setReturnData(resRegister);
            if (resRegister.getCode() == 10000) {
                logEntity.setUserCode(resRegister.getUserCode());
                logEntity.setCustId(resRegister.getCustId());
                logEntity.setUserStatus(resRegister.getUserStatus());
                logEntity.setRegSuccess(1);
            } else {
                logEntity.setRegSuccess(0);
            }
        }
        bizYespayRegLogService.save(logEntity);
    }
}
